/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.exception.ConstraintViolationException;
import ru.miit.elearning.hibernate.dao.CourseDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;

/**
 *
 * @author Cyclone
 */
public class EditLabServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String message = null;

        Session session = null;
        int labId = -1;
        try {
            int courseId = Integer.parseInt(request.getParameter("courseId"));
            labId = Integer.parseInt(request.getParameter("labId"));
            //int directionId = Integer.parseInt(request.getParameter("directionId"));
            int numeral = Integer.parseInt(request.getParameter("number"));
            String title = request.getParameter("title");
            String description = request.getParameter("description");

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            CourseDAO courseDAO = new CourseDAO(session);
            courseDAO.updateCurriculumLevel(labId, courseId, numeral, title, description);
            if (session != null && session.isOpen()) {
                session.getTransaction().commit();
            }
            message = "Практическая работы " + (title != null ? "\"" + title + "\" " : "") + "отредактирована";

            getServletContext().setAttribute("message", message);
            if (courseId != -1) {
                response.sendRedirect("Lab?id=" + labId);
            } else {
                response.sendRedirect("Labs");
            }
        } catch (ConstraintViolationException e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }

            /*
            if (e.getConstraintName().equals("unique_curriculum_level_numeral")) {
            message = "Курс с таким номером уже существует в данном направлении";
            } else {
            message = "Нарушена одна из зависимостей";
            }
             */

            message = "Нарушена одна из зависимостей. Возможно, выбранный номер занят другой практической работой.";
            e.printStackTrace();

            getServletContext().setAttribute("message", message);
            if (labId != -1) {
                response.sendRedirect("Lab?id=" + labId);
            } else {
                response.sendRedirect("Labs");
            }
        } catch (Exception e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }
            message = "Ошибка запроса описания практической работы";
            e.printStackTrace();

            getServletContext().setAttribute("message", message);
            if (labId != -1) {
                response.sendRedirect("Lab?id=" + labId);
            } else {
                response.sendRedirect("Labs");
            }
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
